package util;

import java.io.File;
import java.io.FileInputStream;

/**
 * 自定义类加载器
 * 通过类路径和类名加载指定class文件
 */
public class MyClassLoader extends ClassLoader {

    public static MyClassLoader newInstance(){
        return new MyClassLoader();
    }

    public Class<?> loadClass(String classpath, String name) throws Exception {
        FileInputStream inputStream = null;
        Class<?> aClass = null;
        try {
            File file = new File(classpath);
            inputStream = new FileInputStream(file);
            byte[] bytes = new byte[(int) file.length()];
            inputStream.read(bytes);
            aClass = findLoadedClass(name);
            if (aClass == null) {
                aClass = defineClass(name, bytes, 0, bytes.length);
                resolveClass(aClass);
            }
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                }
            }
        }
        return aClass;
    }

}
